package com.zyw.controller;


import com.zyw.enums.ManagermentSystemEnum;
import com.zyw.exception.ManagermentSystemException;
import com.zyw.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {


    //跳转到登录页面
    @GetMapping("/login-ui")
    public String loginUI(Model model){



        return "user/login";

    }

    @PostMapping("/login")
    @ResponseBody
    public ResultVO login(String username, String password){
        if (StringUtils.isEmpty(username)|| StringUtils.isEmpty(password)){
            log.info("【用户登录】用户名或密码不能为空！ username={} password={}",username,password);
            throw new ManagermentSystemException(ManagermentSystemEnum.LOGIN_BLANK);
        }

        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            log.info("【用户登录】用户名错误！ username={} password={}",username,password);
            throw new ManagermentSystemException(ManagermentSystemEnum.LOGIN_USERNAME_ERROR);
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            log.info("【用户登录】密码密码错误！ username={} password={}",username,password);
            throw new ManagermentSystemException(ManagermentSystemEnum.LOGIN_PASSWORD_ERROR);
        }

        return new ResultVO(0,"",null);
    }


    @GetMapping("/index-ui")
    public String indexUI(){
        return "index";
    }

    @GetMapping("/unanthorized")
    public String unanthorized(){
        return "demo";
    }





}
